package com.rookie.controller;

import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import com.rookie.common.lang.Result;
import com.rookie.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * 登录页的前端控制器
 */
@RestController
public class LoginController {

    @Autowired
    private Producer producer;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 生成验证码
     */
    @GetMapping("captcha")
    public Result captcha() throws IOException {
        String key = UUID.randomUUID().toString().replace("-", "");
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = "data:image/jpeg;base64," + encoder.encode(outputStream.toByteArray());
        redisUtil.hset("captcha", key, code, 120);
        Map<Object, Object> map = MapUtil.builder().put("key", key).put("captchaImg", base64Img).build();
        return Result.success(map);
    }

}
